package com.prj.ufdm.file.dao._impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.mongodb.client.result.UpdateResult;
import com.prj.ufdm.file.dao.WholeFileDao;
import com.prj.ufdm.file.enums.MSFileConstants;
import com.prj.ufdm.file.enums.WholeFileStatusEnum;
import com.prj.ufdm.file.model.WholeFile;

@Repository
public class WholeFileDaoImpl implements WholeFileDao {

	@Autowired
	MongoTemplate mongoTemplate;
	
	/**
	 * 保存文件信息
	 * @param file
	 * @param metaData
	 * @return
	 * @throws Exception
	 */
	@Override
	public WholeFile insertWholeFile(WholeFile wholeFile) throws Exception {
		return mongoTemplate.insert(wholeFile,MSFileConstants.MONGO_COLLECTION_NAME);
	}
	
	/**
	 * 修改文件信息
	 * @param file
	 * @param metaData
	 * @return
	 * @throws Exception
	 */
	@Override
	public UpdateResult updateWholeFile(WholeFile wholeFile) throws Exception {
		Query query = Query.query(Criteria.where("_id").is(wholeFile.getId()));
		Update update = new Update();
		update.set("fileStatus", wholeFile.getFileStatus());
		update.set("listChunkFile", wholeFile.getListChunkFile());
		return mongoTemplate.updateFirst(query, update, MSFileConstants.MONGO_COLLECTION_NAME);
	}
	
	/**
	 * 根据ID查询
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public WholeFile findWholeFileByWholeFileId(String id) throws Exception {
		Query query = Query.query(Criteria.where("_id").is(id));
		return mongoTemplate.findOne(query, WholeFile.class, MSFileConstants.MONGO_COLLECTION_NAME);
	}
	
	/**
	  *  根据fileHash查询
	 * @param fileHash
	 * @return
	 * @throws Exception
	 */
	@Override
	public WholeFile findWholeFileByWholeFileHash(String wholeFileHash) throws Exception {
		Query query = Query.query(Criteria.where("fileHash").is(wholeFileHash));
		List<WholeFile> listWholeFile = mongoTemplate.find(query, WholeFile.class, MSFileConstants.MONGO_COLLECTION_NAME);
		if(listWholeFile!=null && listWholeFile.size()>0) {
			for(WholeFile wholeFile : listWholeFile) {
				// 判断是否上传成功
				if(WholeFileStatusEnum.WHILE_FILE_STATUS_1.getCode().equals(wholeFile.getFileStatus())) {
					return wholeFile;
				}
			}
		}
		return null;
	}
	
}
